package com.horoscope.astrology.zodiac.signs.free.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.adapter.ProfileAdapter
import com.horoscope.astrology.zodiac.signs.free.bean.BaseBean
import com.horoscope.astrology.zodiac.signs.free.bean.CityInfo
import com.horoscope.astrology.zodiac.signs.free.bean.UserBean
import com.horoscope.astrology.zodiac.signs.free.network.NetworkEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.utils.ConstellationUtil
import com.horoscope.astrology.zodiac.signs.free.utils.Logger
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectBornTime
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectBornTime.Companion.getGenerateDialog
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectCity
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectGenderOrStatus
import com.horoscope.astrology.zodiac.signs.free.view.DatePicker
import com.jeremyliao.liveeventbus.LiveEventBus
import java.util.*

/**
 * 用户详情
 */
class ProfileActivity : BaseActivity() {

    private var mDialogGenderOrStatus: DialogSelectGenderOrStatus? = null
    var tag = 1
    var adapter: ProfileAdapter? = null
    private val headName =
        arrayOf("Name", "Gender", "Birthday", "Birthplace", "Marital Status", "Born Time")
    private var headVal = arrayOfNulls<String>(headName.size)
    private var mLinearLayoutManager: LinearLayoutManager? = null
    private var userBean: UserBean? = null
    private var datePicker: DatePicker? = null
    private var selectBornTime: DialogSelectBornTime? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_profile)
        userBean = AppSettingManager.readObject("user_info")
        initView()
        val intent = Intent()
        this@ProfileActivity.setResult(RESULT_OK, intent)
    }

    private fun initView() {
        if (supportActionBar != null) supportActionBar!!.hide()
        initTitleBar(
            this,
            R.id.btn_back_edit_name,
            R.id.text_view_back_title,
            getString(R.string.label_profile)
        )

        headVal = arrayOf(
            userBean!!.name,
            userBean!!.gender,
            userBean!!.birthday,
            userBean!!.bornPlace,
            userBean!!.marial_status,
            userBean!!.bornTime
        )
        mRecyclerView =
            findViewById(R.id.recycle_profile)
        mLinearLayoutManager = LinearLayoutManager(this)
        mRecyclerView.layoutManager = mLinearLayoutManager
        initAdapter()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_USER_NAME) {
            var userName = data?.getStringExtra("UserName")
            userName = userName!!.replace("[\\t\\n\\r]".toRegex(), " ").trim { it <= ' ' }
            if (userName.isEmpty()) return
            compareName(headVal[0], userName, "name")
            headVal[0] = userName
            updateRecyclerView(0, userName)
            userBean!!.name = Objects.requireNonNull(userName)
            saveUserBean(userBean)
        }
        if (resultCode == RESULT_BORN_PLACE) {
            var bornPlace = data?.getStringExtra("BornPlace")
            bornPlace = bornPlace!!.replace("[\\t\\n\\r]".toRegex(), " ").trim { it <= ' ' }
            if (bornPlace.isEmpty()) return
            headVal[3] = bornPlace
            updateRecyclerView(3, bornPlace)
            userBean!!.bornPlace = bornPlace
            saveUserBean(userBean)
        }
    }

    private fun updateRecyclerView(index: Int, str: String?) {
        adapter!!.update(index, str)
    }

    private fun initAdapter() {
        adapter = ProfileAdapter(headName, headVal)
        mRecyclerView.adapter = adapter
        adapter!!.setOnClickedListener { _, position ->
            when (position) {
                0 -> {
                    val intentUserName = ProfileToNameActivity.generateIntent(
                        this@ProfileActivity, "UserNameEdit"
                    )
                    intentUserName.putExtra("UserName", headVal[0])
                    startActivityForResult(intentUserName, 1)
                }
                1 -> {
                    tag = 1
                    mDialogGenderOrStatus = DialogSelectGenderOrStatus(tag, "ProfileActivity")
                    showDialog(mDialogGenderOrStatus)
                }
                2 -> {
                    datePicker =
                        DatePicker(this@ProfileActivity)
                    datePicker!!.ShowDatePick(0, "ProfileActivity")
                }
                3 -> {
                    val dialog = DialogSelectCity(null)
                    dialog.show(supportFragmentManager, "TTy")
                    dialog.setClickListener(object :
                        DialogSelectCity.ICityOnClick {
                        override fun onCityClick(bean: CityInfo) {
                            val place = (bean.name + ", " + bean.adminName1
                                    + ", " + bean.countryName)
                            userBean!!.bornPlace = place
                            compareName(headVal[3], place, "born_place")
                            updateRecyclerView(3, place)
                            dialog.dismiss()
                        }
                    })
                }
                4 -> {
                    tag = 2
                    mDialogGenderOrStatus = DialogSelectGenderOrStatus(tag, "ProfileActivity")
                    showDialog(mDialogGenderOrStatus)
                }
                5 -> {
                    val time = userBean!!.bornTime
                    var h = ""
                    var min = ""
                    if (time.isNotEmpty()) {
                        val array = time.split(":").toTypedArray()
                        if (array.size == 2) {
                            h = array[0]
                            min = array[1].substring(0, 2)
                        }
                    }
                    selectBornTime = getGenerateDialog(itemOnClick, h, min)
                    selectBornTime!!.show(supportFragmentManager, "UU")
                }
            }
        }
    }

    private val itemOnClick =
        View.OnClickListener { view ->
            when (view.id) {
                R.id.text_view_ok -> {
                    val time = selectBornTime!!.getTime()
                    userBean!!.bornTime = time
                    selectBornTime!!.dismiss()
                    updateRecyclerView(5, time)
                    saveUserBean(userBean)
                }
            }
        }

    private fun saveUserBean(userBean: UserBean?) {
        AppSettingManager.saveObject(userBean!!, "user_info")
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        return
    }

    private fun compareName(oldStr: String?, newStr: String, type: String) {
        if (oldStr != newStr) {
            NetworkEngine.postUpdateUserForKey(type, newStr, object : NetworkListener<BaseBean>() {
                override fun onSuccess(t: BaseBean) {
                    Logger.debug("ProfileActivity", "update user success")
                }
            })

        }
    }

    override fun onResume() {
        super.onResume()
        LiveEventBus.get("DoneProfileActivity", String::class.java)
            .observeSticky(this, Observer<String?> { t ->
                t?.let {
                    mDialogGenderOrStatus?.dismiss()
                    if (tag == 1) {
                        compareName(headVal[1], t, "gender")
                        headVal[1] = t
                        updateRecyclerView(1, headVal[1])
                        Objects.requireNonNull(userBean)!!.gender = headVal[1]!!
                    } else {
                        compareName(headVal[4], t, "marital_status")
                        headVal[4] = t
                        updateRecyclerView(4, headVal[4])
                        Objects.requireNonNull(userBean)!!.marial_status = headVal[4]!!
                    }
                    saveUserBean(userBean)
                }
            })

        LiveEventBus.get("AlertDialogDateProfileActivity", Bundle::class.java)
            .observeSticky(this, Observer { bundle ->
                val year = bundle.getInt("year")
                val month = bundle.getInt("moth")
                val day = bundle.getInt("day")
                userBean!!.constellationName =
                    ConstellationUtil.getConstellationName(month - 1, day)
                saveUserBean(userBean)
                val monthTemp = if (month < 10) {
                    "0$month"
                } else {
                    month.toString()
                }
                val dayTemp = if (day < 10) {
                    "0$day"
                } else {
                    day.toString()
                }
                val birthdayStr = "$monthTemp-$dayTemp-$year"
                compareName(headVal[2], birthdayStr, "birthday")
                headVal[2] = birthdayStr
                Objects.requireNonNull(userBean)!!.birthday = headVal[2]!!
                saveUserBean(userBean)
                updateRecyclerView(2, headVal[2])
            })
    }

    private fun showDialog(dialog: DialogFragment?) {
        if (dialog == null) return
        dialog.show(supportFragmentManager, dialog::class.java.simpleName)
    }

    companion object {
        private const val RESULT_OK = 4
        private const val RESULT_USER_NAME = 2
        private const val RESULT_BORN_PLACE = 3
    }
}